<template>
  <div style="background-color: rgba(255, 255, 255, 1);height:100%">
    <div class="top">
      <div class="left" style="float:left;margin-left:30px;">
        <Icon type="md-arrow-round-down"/>
        <i>批量导入</i>
      </div>
    </div>
    <div class="bottom" style="margin:0 auto">
      <div v-if="progress===false">
        <Steps :current="current" style="height:100px;padding-left:22%">
          <Step title="上传文件"></Step>
          <Step title="执行导入"></Step>
          <Step title="导入完成"></Step>
        </Steps>

        <Row class="first" v-if="current===0">
          <ul>
            <li>
              <Col span="3">
                <div class="left">
                  <Icon type="md-cloud-download" size="70"/>
                </div>
              </Col>
              <Col span="21">
                <div class="right">
                  <h3 style="margin-bottom:6px;">填写导入设备的信息</h3>
                  <p style="margin-bottom:6px;">请按照数据模板的格式准备导入数据，模板中的表头名称不可更改，表头行不能删除，单次导入的数据不超过1000条。</p>
                  <a style="margin-bottom:6px;color:blue;cursor: pointer"
                     href="http://irest.oss-cn-hangzhou.aliyuncs.com/device.xls">下载模板</a>
                </div>
              </Col>
            </li>
            <li>
              <Col span="3">
                <div class="left">
                  <Icon type="md-cloud-upload" size="70"/>
                </div>
              </Col>
              <Col span="21">
                <div class="right">
                  <h3 style="margin-bottom:6px;">上传填好的信息表</h3>
                  <p style="margin-bottom:6px;">文件后缀名必须为xsl或xlsl(即excel格式)，文件大小不超过10M</p>
                  <Upload
                    :action="uploadAction"
                    :max-size="10240"
                    :format="['xls', 'xlsl']"
                    :headers="uploadHeaders"
                    :before-upload="beforeUpload"
                    :on-format-error="handleFormatError"
                    :on-exceeded-size="handleMaxSize"
                    :on-success="handleSuccess"
                    :on-remove="handleRemove"
                  >
                    <p v-if="upload" style="margin-bottom:6px;color:blue;cursor: pointer">上传文件</p>
                  </Upload>
                </div>
              </Col>
            </li>
            <!--            <li>-->
            <!--              <Col span="3">-->
            <!--                <div class="left">-->
            <!--                  <Icon type="md-alert" size="70"/>-->
            <!--                </div>-->
            <!--              </Col>-->
            <!--              <Col span="21">-->
            <!--                <div class="right">-->
            <!--                  <h3 style="margin-bottom:10px;">选择数据重复时的处理方式</h3>-->
            <!--                  <Row>-->
            <!--                    <Select v-model="bloc.importExcel.dispose" style="width:200px;margin-right:20px;"-->
            <!--                            placeholder="">-->
            <!--                      <Option v-for="(item,index) in disposeList" :value="index" :key="index" style="height: 20px">{{-->
            <!--                        item }}-->
            <!--                      </Option>-->
            <!--                    </Select>-->
            <!--                    <i>查重规则:设备编号</i>-->
            <!--                  </Row>-->
            <!--                </div>-->
            <!--              </Col>-->
            <!--            </li>-->
          </ul>
        </Row>

        <div class="second" v-if="current===1">
          <ul>
            <li>
              <Col>
              <Icon type="ios-checkmark-circle-outline" size="70" color="#4bd863"/>
              <div class="right">
                <h3>正常数量条数</h3>
                <p>{{bloc.excelError.normalNum}}条</p>
              </div>
              </Col>
            </li>
            <li>
              <Col>
              <Icon type="ios-alert-outline" size="70" color="#ff700b"/>
              <div class="right">
                <h3>异常数量条数</h3>
                <p>{{bloc.excelError.errorNum}}条</p>
              </div>
              </Col>
            </li>
          </ul>
        </div>
        <div class="third" v-if="current===2">
          <Icon type="ios-checkmark-circle-outline" size="100" color="#4bd863"/>
          <h1>批量导入完成</h1>
          <p>成功导入设备数量{{bloc.successData}}条</p>
        </div>

        <div class="button">
          <Button type="primary" @click="next" style="margin-right:10px" v-if="current!==2">下一步</Button>
          <Button style="border:1px solid #499ffe;color:#0079fe" v-if="current===1" @click="current=0">重新上传</Button>
          <Button type="primary" v-if="current===2" @click="toDevices">完成</Button>
        </div>

        <div class="abnormal" v-if="current===1 && bloc.excelError.errorNum>0">
          <h3>异常提示：</h3>
          <ul v-for="(item,index) in bloc.excelError.errorHint" :key="index">
            <li>{{item}}</li>
          </ul>
        </div>

      </div>

      <div class="progress" v-if="progress===true">
        <Progress :percent="percent"/>
      </div>

    </div>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { DevicesBloc } from "./DevicesBloc";
import { store } from "@/store/Store";
import { baseUrl } from "@/base/Request";
import XLSX from "xlsx";

@Component({
  components: {},
})
export default class extends Vue {
  current: any = 0;
  progress: boolean = false;
  percent: number = 0;
  upload: boolean = true;
  bloc = new DevicesBloc();
  disposeList: any = {
    COVER: "覆盖导入",
    SKIP: "跳过数据",
    IMPORT: "依然导入",
  };

  next() {
    if (this.current === 2) {
      this.current = 0;
    } else if (this.current === 1) {
      let that = this;
      if (that.bloc.excelError.errorNum > 0) {
        that.$Message.error(
          `当前表格有${that.bloc.excelError.errorNum}条错误，请修改之后重新上传`
        );
      } else if (that.bloc.excelError.errorNum === 0) {
        this.progress = true;
        that.bloc.getDeviceBatchExcel(that.bloc.importExcel.url);
        if (that.percent < 100) {
          setInterval(function () {
            that.percent += 1;
            if (that.percent >= 100) {
              if (that.current < 2) {
                that.current += 1;
              }
              that.progress = false;
              // that.percent=0;
              return false;
            }
          }, 50);
        }
      }
    } else {
      if (this.excel) {
        this.current += 1;
        this.upload = true;
        this.bloc.getErrorExcel(this.bloc.importExcel.url);
      } else {
        this.$Message.error("请先上传excel表");
      }
    }
  }

  get uploadHeaders() {
    return {
      Authorization: "Bearer " + store.state.auth.accessToken,
    };
  }
  get uploadAction() {
    return `${baseUrl}/api/upload/packet`;
  }

  handleFormatError(file) {
    this.$Message.error("文件格式不正确");
  }

  handleMaxSize(file) {
    this.$Message.error("文件不能超出10M");
  }

  beforeUpload(file) {
    let _this = this;
    // 使返回的值变成Promise对象，如果校验不通过，则reject，校验通过，则resolve
    return new Promise(function (resolve, reject) {
      // readExcel方法也使用了Promise异步转同步，此处使用then对返回值进行处理
      _this.readExcel(file).then(
        (result) => {
          // 此时标识校验成功，为resolve返回
          const isLt10M = file.size / 1024 / 1024 < 10;
          if (!isLt10M) {
            _this.$Message.error("文件大小不能超过10MB!");
          }
          if (isLt10M && result) {
            _this.excel = true;
            resolve("校验成功!");
          } else {
            reject(false);
          }
        },
        (error) => {
          // 此时为校验失败，为reject返回
          _this.$Message.error(error);
          reject(false);
        }
      );
    });
  }

  workbook: object = {};
  excel = false;

  readExcel(file) {
    // 解析Excel
    let _this = this;
    return new Promise(function (resolve, reject) {
      // 返回Promise对象
      const reader = new FileReader();
      reader.onload = (e) => {
        // 异步执行
        try {
          // 以二进制流方式读取得到整份excel表格对象
          if (!e.target) {
            return false;
          }
          let data = e.target.result;
          _this.workbook = XLSX.read(data, { type: "binary" });
          console.log(_this.workbook);
        } catch (e) {
          reject(e.message);
        }
        // 表格的表格范围，可用于判断表头是否数量是否正确
        let fromTo = "";
        // 遍历每张表读取
        for (let sheet in _this.workbook["Sheets"]) {
          let sheetInfos = _this.workbook["Sheets"][sheet];
          let locations: Array<string> = []; // A1,B1,C1...
          if (_this.workbook["Sheets"].hasOwnProperty(sheet)) {
            fromTo = sheetInfos["!ref"]; // A1:B5
            if (fromTo === undefined) {
              return;
            }
            locations = _this.getLocationsKeys(fromTo);
            console.log(fromTo);
          }
          console.log(locations);
          if (sheetInfos[locations[0]] !== undefined) {
            if (
              sheetInfos[locations[0]].v != "设备编号" ||
              sheetInfos[locations[1]].v != "设备分类" ||
              sheetInfos[locations[2]].v != "设备型号"
            ) {
              // 校验失败reject
              reject("请下载模板填写设备信息，再进行上传");
            }
          }
          // for (let i = 0; i < locations.length; i++) {
          //   console.log('sheetInfos[locations[i]', sheetInfos[locations[i]])
          //   if (sheetInfos[locations[i]] !== undefined) {
          //     let value = sheetInfos[locations[i]].v;
          //     if (value != i) {// 自定的校验规则，自由实现即可
          //       // 校验失败reject
          //       reject(locations[i] + '\'s parameter isn\'t ' + i);
          //     }
          //   }
          // }

          // 校验成功resolve
          resolve(true);
        }
      };
      reader.readAsBinaryString(file);
    });
  }

  getLocationsKeys(range) {
    // A1:B5输出 A1,B1...，如果超过26个就会出现，A1:AA1情况，以此类推，也可能出现BA1（BZ1）
    console.log(range);
    let rangeArr = range.split(":");
    let startString = rangeArr[0];
    let endString = rangeArr[1];

    var reg = /[A-Z]{1,}/g;
    let end = endString.match(reg)[0];

    let total = 0; // 共有多少个
    for (let index = 0; index < end.length; index++) {
      total +=
        Math.pow(26, end.length - index - 1) * (end.charCodeAt(index) - 64);
    }

    let result: Array<string> = [];
    for (let i = 0; i < total; i++) {
      // console.log(typeof (i))
      result.push(this.getCharFromIndex(i) + "1");
    }
    return result;
  }

  getCharFromIndex(index) {
    console.log(typeof index);
    let a = parseInt((index / 26).toString()); // 整除
    let b = index % 26; // 余数
    let returnChar = String.fromCharCode(b + 65); // 最后一个字符
    while (a > 0) {
      b = a % 26;
      a = parseInt((a / 26).toString());
      // 从后生成字符，向前推进
      returnChar = String.fromCharCode(b + 65 - 1) + returnChar;
    }
    return returnChar;
  }

  handleRemove() {
    this.upload = true;
    this.excel = false;
  }

  handleSuccess(res, file) {
    this.upload = false;
    this.bloc.importExcel.url = res.data.url;
  }

  toDevices() {
    this.$router.push({ name: "设备管理" });
    this.current = 0;
  }

  mounted() {
    // console.log(this.current)
  }
}
</script>
<style lang="less" scoped>
.top {
  height: 50px;
  width: 100%;
  border-bottom: 1px solid rgba(204, 204, 204, 1);
  font-size: 18px;
  line-height: 50px;
}

.bottom {
  padding: 100px 80px 50px 80px;
  // display: flex;
  .first {
    height: 300px;
    margin-left: 22%;
    margin-right: 20%;

    ul {
      height: 120px;

      li {
        border: 1px solid #e9e9e9;
        height: 120px;
        margin-bottom: 20px;

        .left {
          background-color: #f5f5f5;
          border-right: 1px solid #e9e9e9;
          height: 120px;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .right {
          padding: 20px 15px;
        }
      }
    }
  }

  .second {
    height: 300px;
    margin-left: 22%;
    margin-right: 20%;

    ul {
      height: 120px;

      li {
        border: 1px solid #e9e9e9;
        height: 120px;
        margin-bottom: 20px;
        padding: 20px 40px;
        justify-content: flex-start;
        display: flex;

        .right {
          display: flex;
          flex-direction: column;
          margin-left: 30px;
          padding-top: 10px;

          p {
            margin-top: 10px;
            color: blue;
          }
        }
      }
    }
  }

  .third {
    height: 200px;
    // margin-left: 44%;
    // margin-right: 42%;
    display: flex;
    flex-direction: column;
    text-align: center;
    justify-content: space-between;
  }

  .button {
    margin: 50px auto;
    display: flex;
    justify-content: center;
  }

  .abnormal {
    margin-left: 22%;
    margin-right: 20%;
    min-height: 300px;
    background-color: #fbfbfb;
    border: 1px solid #e9e9e9;
    color: #ff6a00;
    padding: 30px 20px;

    ul {
      li {
        margin-top: 10px;
      }
    }
  }

  .progress {
    margin-left: 22%;
    margin-right: 20%;
  }
}

/deep/ .ivu-select-item {
  border: none !important;
}

/deep/ .ivu-upload-list {
  margin-top: -19px !important;
}

/deep/ .ivu-steps {
  padding-left: 0 !important;
}
</style>
